package com.hczt.springcloud.oauthresource.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;

/**
 * 精诚所至，金石为开。
 * 石の上にも三年;陽気の発する所金石亦透る。
 * Faith moves mountains.
 *
 * @author marvin.ma
 * @create 2017-12-17 16:18
 * @desc 资源配置
 **/
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Autowired
    Environment env;

    @Bean
    public RemoteTokenServices remoteTokenServices() {
        RemoteTokenServices remoteTokenServices = new RemoteTokenServices();
        remoteTokenServices.setCheckTokenEndpointUrl(p("oauth.check_token"));
        remoteTokenServices.setClientId(p("oauth.client_id"));
        return remoteTokenServices;
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .formLogin().loginPage("/login.html").loginProcessingUrl("/login").permitAll()
                .and()
                    .authorizeRequests()
                    .antMatchers("/login", "/oauth/**", "/public/**").permitAll()
                .anyRequest()
                .authenticated()
                .and().csrf().disable();
        //http
        //        .csrf().disable()
        //        .exceptionHandling()
        //        .authenticationEntryPoint((request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED))
        //        .and()
        //        .authorizeRequests()
        //        //.antMatchers("/user/**").access("hasRole('ADMIN')")
        //        .anyRequest().authenticated()
        //        .and()
        //        .exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
        //.httpBasic();
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        System.out.println("==========================ResourceServerSecurityConfigurer==========================");
        resources.resourceId("android");


    }

    private String p(String key) {
        return env.getProperty(key);
    }
}
